//
//  InvoiceDetailViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/24.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//
#define viewHeight 40

#import "InvoiceDetailViewController.h"
#import "TopBackView.h"
#import "RootViewController.h"
#import "Common.h"
#import "ActionSheetPicker.h"
#import "area.h"
#import "Common.h"

#define AreaBtnTag 100
#define KeepBtnTag 200
#define FieldTag 500
#define MySetValue(dict, value) ((!dict[value] || [dict[value] isKindOfClass:[NSNull class]])?@"":dict[value])

@interface InvoiceDetailViewController ()<UITextFieldDelegate,UIActionSheetDelegate,UIAlertViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
{
    Common * Com;
    area * AREA;
    NSMutableDictionary * dic;

}
@property (nonatomic,strong) UIScrollView *scrollView;

@property (nonatomic,strong) UITextField *priceField;//价格
@property (nonatomic,strong) UITextField *titleField;//抬头
@property (nonatomic,strong) UITextField *nameField;//姓名
@property (nonatomic,strong) UITextField *phoneField;//电话
@property (nonatomic,strong) UITextField *addressField;//详细地址
@property (nonatomic,strong) UITextField *areaField;
@property (nonatomic,strong) UITextField *contentField;//开票内容
@property (nonatomic,strong) UITextField *mailField;//邮寄费用


@property (nonatomic, strong) NSMutableArray *provienceArray;
@property (nonatomic, strong) NSArray *cityArray;
@property (nonatomic, strong) NSArray *areaArray;


@end

@implementation InvoiceDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    dic = [NSMutableDictionary dictionary];
    self.provienceArray = [NSMutableArray array];
    self.cityArray = [NSArray array];
    self.areaArray = [NSArray array];
    
    Com = [[Common alloc]init];
    AREA = [[area alloc]init];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"发票中心"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = WhiteColor;
    
    [self initSubViews];
}


-(void)postDataSourceToInternet
{
    //拼接图片url
//    NSString *urlString = [NSString stringWithFormat:@"%@invoice/create",Main_interface];
    
    NSString *string = [self.areaField.text stringByAppendingString:self.addressField.text];
    string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    [dic setObject:self.idString forKey:@"orderids"];
    [dic setObject:self.titleField.text forKey:@"title"];
    [dic setObject:string forKey:@"address"];
    [dic setObject:self.nameField.text forKey:@"addressee"];
    [dic setObject:self.phoneField.text forKey:@"contact"];
//    [dic setObject:<#(nonnull id)#> forKey:@"comment"];
    

    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:invoice_create parms:dic finishedBlock:^(id responseObj) {
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        NSLog(@"%@",dictionary);
        
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}


-(void)initSubViews
{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    [self.view addSubview:self.scrollView];
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    
    NSArray *array = @[@"开票金额",
                       @"开票抬头",
                       @"开票内容",
                       @"收件人",
                       @"收件电话",
                       @"所在地区",
                       @"详细地址",
                       @"邮寄费用"];
    
    self.priceField = [[UITextField alloc]init];
    self.titleField = [[UITextField alloc]init];
    self.contentField = [[UITextField alloc]init];
    self.nameField = [[UITextField alloc]init];
    self.phoneField = [[UITextField alloc]init];
    self.addressField = [[UITextField alloc]init];
    self.mailField = [[UITextField alloc]init];
    self.areaField = [[UITextField alloc]init];
    
    
    NSArray *fieldArray = @[self.priceField,self.titleField,self.contentField,self.nameField,self.phoneField,self.areaField,self.addressField,self.mailField];
    
    for (int i = 0; i < array.count; i++) {
        
        UITextField *textF = (UITextField *)fieldArray[i];
        textF.delegate = self;
        textF.font = Font(15);
        
        
        UIView *view = [self backViewWithString:array[i] andTextField:textF andInteger:i];
        [self.scrollView addSubview:view];
    }
    
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    infoButton.frame = CGRectMake(50, 64 + 40 * (array.count + 2 ), screenWidth - 50 * 2, 40);
    [infoButton setTitle:@"提交信息" forState:UIControlStateNormal];
    [infoButton setTitleColor:BlackColor forState:UIControlStateNormal];
    infoButton.titleLabel.font = Font(15);
    [infoButton addTarget:self action:@selector(infoButtonAction) forControlEvents:UIControlEventTouchUpInside];
    infoButton.layer.cornerRadius = 5;
    infoButton.layer.borderColor = GrayColor.CGColor;
    infoButton.layer.borderWidth = 0.5;

    [self.scrollView addSubview:infoButton];
    
    
    //获取地区
    UIButton *areaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    areaButton.frame = CGRectMake(0,0,200 * kWidth,30);
    [areaButton addTarget:self action:@selector(areaButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.areaField addSubview:areaButton];
    
    [self valueString];
    
}

-(void)valueString
{
    
    self.priceField.text = [NSString stringWithFormat:@"￥%@",self.price];
    self.priceField.userInteractionEnabled = NO;
    self.priceField.borderStyle = UITextBorderStyleNone;
    
    self.contentField.text = @"运费";
    self.contentField.borderStyle = UITextBorderStyleNone;
    self.priceField.userInteractionEnabled = NO;
    
    self.mailField.text = @"到付";
    self.mailField.borderStyle = UITextBorderStyleNone;
    self.mailField.userInteractionEnabled = NO;
}

-(void)infoButtonAction
{
    [self postDataSourceToInternet];
}


-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
    
}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(UIView *)backViewWithString:(NSString *)string andTextField:(UITextField *)field andInteger:(NSInteger)integer
{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0,  integer * viewHeight, screenWidth, viewHeight)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(14, 10, 80, 20)];
    label.text = string;
    label.font = Font(15);
    [view addSubview:label];
    
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, viewHeight - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = GrayColor;
    [view addSubview:lineL];
    
    field.frame = CGRectMake(CGRectGetMaxX(label.frame) , 5, 200 * kWidth, 30);
    field.borderStyle = UITextBorderStyleRoundedRect;
    field.font = Font(15);
    field.delegate = self;
    [view addSubview:field];
    
    
    return view;
}



-(void)areaButtonAction{
    
    [self.view endEditing:YES];
    
    _provienceArray = nil;
    _cityArray = nil;
    _areaArray = nil;
    
    _provienceArray = [AREA selectAreaWithFArea:nil withTarea:nil withFarea:1];
    _cityArray = [AREA selectAreaWithFArea:@"北京市" withTarea:nil withFarea:2];
    _areaArray = [AREA selectAreaWithFArea:@"北京市" withTarea:@"市辖区" withFarea:3];
    
        
    UIImageView * image = (UIImageView*)[self.view viewWithTag:1000];
    image.transform = CGAffineTransformMakeRotation(M_PI_2);
    UIPickerView *education = [[UIPickerView alloc] init];
    ActionSheetPicker *actionSheet=[[ActionSheetPicker alloc]initWithTarget:self successAction:@selector(selectOK:) cancelAction:nil origin:education];
    
    CGRect pickerFrame = CGRectMake(0, 40, actionSheet.viewSize.width, 216);
    [education setFrame:pickerFrame];
    education.delegate = self;
    education.dataSource = self;
    //pickview  左选择按钮的文字
    UIButton *leftBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setTitle:@"取消"forState:UIControlStateNormal];
    leftBtn.frame=CGRectMake(0, 0, 50, 45);
    [leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *leftIte=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    //pickview    右选择按钮的文字
    UIButton *rightBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    rightBtn.frame=CGRectMake(0, 0, 50, 45);
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *rightIte=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    //将按钮添加到pickerview 上
    [actionSheet setDoneButton:rightIte];
    [actionSheet setCancelButton:leftIte];
    actionSheet.pickerView = education;
    actionSheet.title = @"地址选择";
    [actionSheet showActionSheetPicker];
    NSLog(@"点击的是地区选择");
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{
    NSInteger ss = [pickerView selectedRowInComponent:0];
    NSInteger dd = [pickerView selectedRowInComponent:1];
    
    switch (component) {
        case 0:
        {
            NSDictionary *dict = [_provienceArray objectAtIndex:row];
            NSString *code = MySetValue(dict, @"provinceName");
            if (code.length > 0)
            {
                _cityArray = [AREA selectAreaWithFArea:code withTarea:nil withFarea:2];
                [pickerView reloadComponent:1];
                NSDictionary *cityDict = [_cityArray objectAtIndex:dd];
                NSString * cityFcode = MySetValue(cityDict, @"cityName");
                if (cityFcode.length > 0)
                {
                    _areaArray = [AREA selectAreaWithFArea:code withTarea:cityFcode withFarea:3];
                    [pickerView reloadComponent:2];
                }
            }
        }
            break;
        case 1:
        {
            NSDictionary *dict = [_cityArray objectAtIndex:row];
            NSString *code = MySetValue(dict, @"cityName");
            
            NSDictionary * dics = [_provienceArray objectAtIndex:ss];
            NSString * str = MySetValue(dics, @"provinceName");
            NSLog(@"%@",code);
            
            NSLog(@"%@",str);
            if (code.length > 0) {
                _areaArray = [AREA selectAreaWithFArea:str withTarea:code withFarea:3];
                [pickerView reloadComponent:2];
            }
        }
            break;
        case 2:{
            
        }
            break;
            
        default:
            break;
    }
}


- (void)selectOK:(id)sender{
    
    
    UIPickerView *pick = sender;
    NSInteger row = [pick selectedRowInComponent:0];
    NSDictionary *dict = [_provienceArray objectAtIndex:row];
    NSString *provinceName = MySetValue(dict, @"provinceName");//省名称
    NSString *provinceCode = MySetValue(dict, @"provinceCode");//省编码
    
    
    NSInteger row1 = [pick selectedRowInComponent:1];
    NSDictionary *dict1 = [_cityArray objectAtIndex:row1];
    NSString *cityName = MySetValue(dict1, @"cityName");//市名称
    NSString *citycode = MySetValue(dict1, @"cityCode");//市编码
    
    NSInteger row2 = [pick selectedRowInComponent:2];
    NSDictionary *dict2 = [_areaArray objectAtIndex:row2];
    NSString *countyName = MySetValue(dict2, @"countyName");//县名称
    NSString * countycode = MySetValue(dict2, @"countyCode");//县编码
    
    
    [dic setObject:provinceCode forKey:@"provincecode"];//省编码
    [dic setObject:provinceName forKey:@"provincename"]; //省名称
    [dic setObject:citycode forKey:@"citycode"];//市编码
    [dic setObject:cityName forKey:@"cityname"]; //市名称
    [dic setObject:countycode forKey:@"countycode"];//县编码
    [dic setObject:countyName forKey:@"countyname"]; //县名称
    
    NSString * btnName = [NSString stringWithFormat:@"%@-%@-%@",provinceName,cityName,countyName];
    
    self.areaField.text = btnName;
    
//    [_AreaBtn setTitle:btnName forState:UIControlStateNormal];
    UIImageView * image = (UIImageView*)[self.view viewWithTag:1000];
    image.transform = CGAffineTransformMakeRotation(0);
}

//  跳出的pickerview  显示列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}


//显示pickerview 每个视图的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component

{
    switch (component) {
        case 0:
            return _provienceArray.count;
            break;
        case 1:
            return _cityArray.count;
            break;
        case 2:
            return _areaArray.count;
            break;
        default:
            break;
    }
    return 0;
}

//显示每个pickerview  每行的具体内容

-(UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

{
    
    
    UILabel *lable  = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    lable.adjustsFontSizeToFitWidth = YES;
    lable.textAlignment = NSTextAlignmentCenter;
    
    switch (component) {
        case 0:{
            NSDictionary *dict = [_provienceArray objectAtIndex:row];
            lable.text = MySetValue(dict, @"provinceName");
        }
            
            break;
        case 1:{
            
            NSDictionary *dict = [_cityArray objectAtIndex:row];
            lable.text = MySetValue(dict, @"cityName");
        }
            
            break;
            
        case 2:{
            
            NSDictionary *dict = [_areaArray objectAtIndex:row];
            lable.text = MySetValue(dict, @"countyName");
        }
            
            break;
        default:
            break;
    }
    return lable;
}



#pragma mark UITextField Delegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
        /* 计算偏移量 */
        
        CGFloat height = 258;
        
        CGFloat offsetHeight = CGRectGetMaxY(textField.frame) - (Main_height - height);
        
        if (offsetHeight >= 0) {
            
            self.scrollView.contentInset = UIEdgeInsetsMake(-offsetHeight - 64, 0, 0, 0);

        }
        
        
    } completion:^(BOOL finished) {
        
    }];

}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
      
        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
    } completion:^(BOOL finished) {
        
    }];
}


/**
 return 健收回键盘
 */
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.titleField || textField == self.nameField || textField == self.phoneField || self.addressField) {
        
        [textField resignFirstResponder];
    }
    
    
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
